package org.zjx.core;

import lombok.Getter;
import org.zjx.client.SocketClient;
import org.zjx.resource.ResourceManager;
import org.zjx.service.AddService;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceClient {
    private static ServiceClient instance;
    @Getter
    private final SocketClient client;
    private final Map<Class<?>, Object> proxies = new ConcurrentHashMap<>();

    private ServiceClient(String host, int port) {
        this.client = new SocketClient(new SocketConfig()
                .setServerHost(host)
                .setPort(port)
                .setHeartbeatInterval(30000));
        this.client.connect();
    }

    public static synchronized ServiceClient getInstance() {
        if (instance == null) {
            instance = new ServiceClient(ResourceManager.CONFIG.getHost(), ResourceManager.CONFIG.getPort());
        }
        return instance;
    }

    @SuppressWarnings("unchecked")
    public <T> T getService(Class<T> serviceInterface) {
        return (T) proxies.computeIfAbsent(serviceInterface,
                client::createProxy);
    }

    public void shutdown() {
        client.disconnect();
        instance = null;
    }

    public static void main(String[] args) {
        // 客户端使用
        ServiceClient client = getInstance();
        AddService addService = client.getService(AddService.class);
        System.out.println(addService.add(88,145));
//        client.shutdown();
    }
}
